package jprint.jfx;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import javafx.application.Application;
import javax.swing.JOptionPane;
import jprint.base.AppContext;
import jprint.base.http.Http;
import jprint.base.http.HttpServerLite;
import jprint.jfx.http.ApiHandler;
import jprint.jfx.http.AssetsFileHandler;
import jprint.jfx.webapp.WebViewApp;

/**
 * @author zwz
 * Created on 2021-01-18
 */
public class Main {

    private static Http.HttpServer server;
    private static FileLock fileLock;
    private static Splash splash;

    private static void checkSingleProcess() {
        // 使用文件锁检查是否已经有一个实例在运行
        File lockFile = new File(
            System.getProperty("java.io.tmpdir"), Main.class.getCanonicalName() + ".lock");
        try {
            lockFile.createNewFile();
            FileChannel fileChannel = new RandomAccessFile(lockFile, "rw").getChannel();
            fileLock = fileChannel.tryLock();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (fileLock == null) {
            JOptionPane.showMessageDialog(null,
                                          "程序已经运行，请勿重复运行！",
                                          "提示",
                                          JOptionPane.WARNING_MESSAGE);
            System.exit(1);
        } else {
            lockFile.deleteOnExit();
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    fileLock.release();
                    if (lockFile.exists()) {
                        lockFile.delete();
                    }
                } catch (IOException ignored) {
                    // ignored
                }
            }));
        }
    }

    public static void main(String[] args) {
        checkSingleProcess();
        splash = new Splash();
        splash.setLocationRelativeTo(null);
        splash.setVisible(true);
        WebViewApp.setAppStarting(splash);
        server = HttpServerLite.getInstance(2020);
        setup();
        System.out.println("It works，中文乱码测试!");
        // SwingUtilities.invokeLater(() -> Application.launch(WebViewApp.class, args));
        Application.launch(WebViewApp.class, args);
    }

    private static void setup() {
        AppContext appContext = AppContextImpl.getInstance();
        server.registerHandler(new AssetsFileHandler(appContext.getWebRoot()),
                               new ApiHandler(appContext));
        appContext.setServer(server);
        server.startup();
    }
}
